<?php

namespace app\api\controller;

use Think\Db;
class Passport
 {
    //登录
    public function login(){
        $_SESSION['client_type'] = 'Wxx';//小程序访问
        $_SESSION['Wxx']         = $_POST;
        $encryptedData           = $_POST['encrypted_data'];
        $iv                      = $_POST['iv'];
        $code                    = $_POST['code'];
        $info                    = json_decode($_POST['user_info'],true);
        $signature = $_POST['signature'];

        $tk_id = $_POST['tk_id'];
        if($tk_id) cookie('tk_id', $tk_id);

        $alert     = ['code','iv','encrypted_data'];//错误警示
        foreach($alert as $k=>$v){
            if(!$_POST[$v]){
                $alert['alert'] .= $alert[$k].'为空 ';
            }
        }
        if($alert['alert']){
            return $this->ajaxReturn([],0,$alert);
        }
        $userMdl  = model('Common/Users');
        $rCode    = for_wxx_code($code);
        // p($rCode);
        if (!isset($rCode['openid'])) {
            return $this->ajaxReturn([],0,'获取openid失败');
        }
        $userinfo = $userMdl->where(['wxapp_openid'=>$rCode['openid']])->find();
        if(!$userinfo){
            // 注册
            $info['session_key'] = $rCode['session_key'];
            $userinfo = $userMdl->wxappRegister($info,$rCode['openid']);
        }
        $token = buildToken($userinfo['user_id']);
        $userMdl->where(['user_id'=>$userinfo['user_id']])->update(['token'=>$token,'session_key'=>$rCode['session_key']]);
        $userinfo['token'] = $token;
        $userinfo['session_key'] = $rCode['session_key'];
        return $this->ajaxReturn($userinfo);

    }

    public function ajaxReturn( $data, $code = 1,$msg = '成功'){
        exit(json_encode(['data'=>$data,'code'=>$code,'msg'=>$msg]));
    }

    /**
     * 小程序分享
     */
    public function share()
    {
        $tk_id = input('tk_id', 0);
        cookie('tk_id', $tk_id, 300);
    }

    
}